clear all;
close all;
clc;


R = 100;
C = 33e-6;

RC = R*C;

Tmod = 10*RC;
T = RC / 1000;

t = 0:T:Tmod;

% sigma function
E = 0*(t<Tmod/4)+3*(t>=Tmod/4);

%plot(t,E);

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1);
dU(1) = 0;
U2 = U;

for k = 2:length(t)
    
    U(k) = U(k-1) + dU(k-1)*T;
    dU(k) = (E(k) - U(k)) / RC;
    
    U2(k) = (RC*U2(k-1) + E(k)*T) / (RC + T);
end

figure;
plot(t, E, t, U, t, U2)
xlabel('t, sec');
ylabel('U, V');

% random
E = 7*randn(1,length(t));

%plot(t,E);

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1);
dU(1) = 0;
U2 = U;

for k = 2:length(t)
    
    U(k) = U(k-1) + dU(k-1)*T;
    dU(k) = (E(k) - U(k)) / RC;
    
    
    U2(k) = (RC*U2(k-1) + E(k)*T) / (RC + T);
end

figure;
plot(t, E, t, U, t, U2)
xlabel('t, sec');
ylabel('U, V');

% garmonic
f = 30;
A = 1;
E = A*sin(2*pi*f*t);

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1);
dU(1) = 0;

for k = 2:length(t)
    
    U(k) = U(k-1) + dU(k-1)*T;
    dU(k) = (E(k) - U(k)) / RC;

end

plot(t,E,t,U)

% sweep garmonic
fmin = 1/(Tmod/2);
fmax = 10*fmin; %1/T/2;
f = fmin:((fmax-fmin)/100):fmax;
A = 1;

K = nan(1,length(f));
figure;
for j = 1:length(f)
    E = A*sin(2*pi*f(j)*t);
    U = nan(1, length(t));
    dU = nan(1, length(t));

    U(1) = E(1);
    dU(1) = 0;

    for k = 2:length(t)
    
        U(k) = U(k-1) + dU(k-1)*T;
        dU(k) = (E(k) - U(k)) / RC;
    end
    plot(t,U);
    Us = U(fix(end/2):end);
    K(j) = (max(Us)-min(Us))/2;
end

figure;
plot(f,K);
